<?php
/**
 * Created by IntelliJ IDEA.
 * User: apple
 * Date: 16/10/4
 * Time: 上午10:18
 * 下载丽华网站的数据到rms
 * 网站和rms数据交流API
 * /Applications/XAMPP/xamppfiles/bin/php  /Applications/XAMPP/htdocs/rmsdaemon/index.php Home/LihuaWeb/webOrder
 *
 * 实际命令: /alidata/server/php/bin/php /home/rmsdaemon/index.php  Home/LihuaWeb/getGzWebOrder
 */
namespace Home\Controller;

use Think\Controller;
use Think\Log;
 
class LihuaWebController extends Controller
{

    // 获取北京的订单
    public function getBjWebOrder()
    {
        $this->logFile = C('LOG_PATH') . 'lihuaweborderBj-' . date('y_m_d') . '.log';
        \Think\Log::write('开始获取网站的订单', \Think\Log::INFO, '', $this->logFile);
        
        $connect_str = C('BJRMS_CONNECTSTR');
        $this->webOrder(1, $connect_str);
    }

    // 获取上海的订单
    public function getShWebOrder()
    {
        $this->logFile = C('LOG_PATH') . 'lihuaweborderSh-' . date('y_m_d') . '.log';
        \Think\Log::write('开始获取网站的订单', \Think\Log::INFO, '', $this->logFile);
        
        $connect_str = C('RMS_CONNECTSTR');
        $this->webOrder(3, $connect_str);
    }

    // 获取常州的订单
    public function getCzWebOrder()
    {
        $this->logFile = C('LOG_PATH') . 'lihuaweborderCz-' . date('y_m_d') . '.log';
        \Think\Log::write('开始获取网站的订单', \Think\Log::INFO, '', $this->logFile);
        
        $connect_str = C('RMS_CONNECTSTR');
        $this->webOrder(4, $connect_str);
    }

    // 获取南京的订单
    public function getNjWebOrder()
    {
        $this->logFile = C('LOG_PATH') . 'lihuaweborderNj-' . date('y_m_d') . '.log';
        \Think\Log::write('开始获取网站的订单', \Think\Log::INFO, '', $this->logFile);
        
        $connect_str = C('RMS_CONNECTSTR');
        $this->webOrder(6, $connect_str);
    }

    // 获取苏州的订单
    public function getSzWebOrder()
    {
        $this->logFile = C('LOG_PATH') . 'lihuaweborderSz-' . date('y_m_d') . '.log';
        \Think\Log::write('开始获取网站的订单', \Think\Log::INFO, '', $this->logFile);
        
        $connect_str = C('RMS_CONNECTSTR');
        $this->webOrder(7, $connect_str);
    }

    // 获取无锡的订单
    public function getWxWebOrder()
    {
        $this->logFile = C('LOG_PATH') . 'lihuaweborderWx-' . date('y_m_d') . '.log';
        \Think\Log::write('开始获取网站的订单', \Think\Log::INFO, '', $this->logFile);
        
        $connect_str = C('RMS_CONNECTSTR');
        $this->webOrder(8, $connect_str);
    }

    // 获取广州的订单
    public function getGzWebOrder()
    {
        $this->logFile = C('LOG_PATH') . 'lihuaweborder-' . date('y_m_d') . '.log';
        \Think\Log::write('开始获取网站的订单', \Think\Log::INFO, '', $this->logFile);
        
        $connect_str = C('RMS_CONNECTSTR');
        $this->webOrder(9, $connect_str);
    }

    /**
     * 送网站获取数据,保存到rms中
     */
    public function webOrder($city_id, $connect_str)
    {
        var_dump($connect_str);
        // 订单表
        $orderform_model = M('orderform', 'rms_', $connect_str);
        // 订货表
        $ordergoods_model = M('orderproducts', 'rms_', $connect_str);
        // 活动表
        $orderactivity_model = M('orderactivity', 'rms_', $connect_str);
        // 支付表
        $orderpayment_model = M('orderpayment', 'rms_', $connect_str);
        // 欠单结账表
        $orderclientdebt_model = M('orderclientdebt', 'rms_', $connect_str);
        // 结账单
        $orderfinance_model = M('orderfinance', 'rms_', $connect_str);
        // 状态表
        $orderstate_model = M('orderstate', 'rms_', $connect_str);
        // 日志表action中
        $orderaction_model = M('orderaction', 'rms_', $connect_str);
        // 网站状态表
        $webstatus_model = M('webstatus', 'rms_', $connect_str);
        // 营收状态表
        $orderyingshouexchange_model = M('orderyingshouexchange', 'rms_', $connect_str);
        // 发票,不写入,等分配订单的时候,写入
        $invoice_model = M('invoice', 'rms_', $connect_str);
        // 客户消息
        $notifyclientModel = M('notify_client', 'rms_', $connect_str);
        
        $lihuaweb_conn_str = C('LIHUAWEB_CONNETCSTR');
        // 网站订单表
        $weborder_model = M('order', 'lihua_think_', $lihuaweb_conn_str);
        var_dump($connect_str);
        // 网站产品表
        $webordergood_model = M('order_good', 'lihua_think_', $lihuaweb_conn_str);
        // 网站活动表
        $weborderactivity_model = M('order_activity', 'lihua_think_', $lihuaweb_conn_str);
        // 网站支付表
        $weborderpayment_model = M('order_payment', 'lihua_think_', $lihuaweb_conn_str);
        
        $currentDate = date('Y-m-d');
        $tomorrowDate = date('Y-m-d', strtotime('+1 day'));
        
        $where = array();
        $where['city_id'] = $city_id;
        $where['status'] = 0;
        $where['_string'] = " (pay_status = 1 or pay_status = 2) and (add_time like '" . $currentDate . "%') and (shipping_time is null or shipping_time <  '". $tomorrowDate ."')";
        // $where['shipping_time'] = array('LT', $tomorrowDate);
        // $where['pay_status'] = 2;
        $orderform = $weborder_model->where($where)
            ->limit(50)
            ->order('id desc')
            ->select();
        
        var_dump($weborder_model->getLastSql());
        
        \Think\Log::write('获取' . $weborder_model->getLastSql() . ' ', \Think\Log::INFO, '', $this->logFile);
        
        // 写入日志
        \Think\Log::write('获取' . count($orderform) . '条订单', \Think\Log::INFO, '', $this->logFile);
        foreach ($orderform as $orderValue) {
            
            /**
             * *********************************
             * 订单表处理
             * *********************************
             */
			
			
			if(strpos($orderValue['remark'],'无接触配送') === false){
				$orderValue['remark'] = $orderValue['remark'] . '[无接触配送]';
			}
			
            $orderform_arr = array();
            // 订单号
            $orderform_arr['ordersn'] = $orderValue['sn'];
            // 联系人的姓名
            $orderform_arr['clientname'] = $orderValue['consignee'];
            
            // 用户送餐地址
            if (empty($orderValue['location'])) {
                $orderform_arr['address'] = $orderValue['address'];
            } else {
                $address_tmp = $orderValue['address'];
                $topheader = '';
                for ($i = 0; $i < 10; $i ++) { // 循环十次
                    $toptmp = substr($address_tmp, 0, 1);
                    if ($toptmp == '(') {
                        $topheaderlength = strpos($address_tmp, ')', 1);
                        $topheader = $topheader . substr($address_tmp, 0, $topheaderlength + 1);
                        $address_tmp = substr($address_tmp, $topheaderlength + 1);
                    }
                }
                $location = $this->checkstr($address_tmp, $orderValue['location']); // 去掉重复的地址
                $orderform_arr['address'] = $topheader . $orderValue['location'] . $location;
            }
            
            $orderform_arr['address'] = $this->filter($orderform_arr['address']);
            // 收货人手机
            $orderform_arr['telphone'] = $orderValue['tel'];
            $orderform_arr['telphone'] = $this->filter($orderform_arr['telphone']);
            // 送餐日期
            $orderform_arr['custdate'] = date('Y-m-d');
            // 送餐时间
            if (empty($orderValue['time'])) {
                $orderform_arr['custtime'] = date('H:i:s', time() + 60 * 30);
            } else {
                $orderform_arr['custtime'] = $orderValue['time'];
            }
            // 接单员
            $orderform_arr['telname'] = $orderValue['refer'];
            // 接单时间
            $orderform_arr['rectime'] = date('H:i:s');
            // 接单日期
            $orderform_arr['recdate'] = date('Y-m-d');
            // 订单备注(附言)
            $orderform_arr['beizhu'] = $orderValue['remark'];
            $orderform_arr['beizhu'] = $this->filter($orderform_arr['beizhu']);
			
			
			
			
            if ($city_id == 4) {
                $orderform_arr['beizhu'] = '[网订]' . $orderform_arr['beizhu'];
            }
            
            // 订单总金额
            $orderform_arr['totalmoney'] = $orderValue['original_amount'];
            // 应收金额
            $orderform_arr['shouldmoney'] = $orderValue['amount'];
            // 已付金额
            $orderform_arr['paidmoney'] = $orderValue['money_paid'];
            
            if ($orderValue['pay_type'] == 2) { // 是在线支付
                                                    // 已付金额
                                                    // $orderform_arr['paidmoney'] = 0;
                                                    // 应收金额
                                                    // $orderform_arr['shouldmoney'] = 0;
            } else { // 是货到付款
                         // 已付金额
                         // $orderform_arr['paidmoney'] = 0;
                         // 应收金额
                         // $orderform_arr['shouldmoney'] = 0;
            }
            
            // 发票抬头
            if (! empty($orderValue['inv_payee'])) {
                $orderform_arr['invoiceheader'] = $orderValue['inv_payee'];
            } else {
                $orderform_arr['invoiceheader'] = '';
            }
            // 发票内容
            if (! empty($orderValue['inv_content'])) {
                $orderform_arr['invoicebody'] = $orderValue['inv_content'];
            } else {
                $orderform_arr['invoicebody'] = '工作餐';
            }
            // 纳税人识别号
            if (! empty($orderValue['inv_no'])) {
                if (trim($orderValue['inv_no']) == '无') {
                    $orderform_arr['gmf_nsrsbh'] = '';
                } else {
                    $orderform_arr['gmf_nsrsbh'] = $orderValue['inv_no'];
                }
            } else {
                $orderform_arr['gmf_nsrsbh'] = '';
            }
            // 购买方地址电话
            if (! empty($orderValue['inv_addressandtel'])) {
                $orderform_arr['gmf_dzdh'] = $orderValue['inv_addressandtel'];
            } else {
                $orderform_arr['gmf_dzdh'] = '';
            }
            // 购买方银行账户
            if (! empty($orderValue['inv_bankandaccount'])) {
                $orderform_arr['gmf_yhzh'] = $orderValue['inv_bankandaccount'];
            } else {
                $orderform_arr['gmf_yhzh'] = '';
            }
            // 发票类型
            if ($orderValue['inv_type'] == 2) {
                $orderform_arr['invoicetype'] = '普通票';
            }
            if ($orderValue['inv_type'] == 3) {
                $orderform_arr['invoicetype'] = '电子票';
            }
            
            // 送餐费名称
            $orderform_arr['shippingname'] = '自配送';
            // 送餐费金额
            $orderform_arr['shippingmoney'] = 0;
            
            // 分公司名称（商店）
            if (empty($orderValue['store'])) {
                $orderform_arr['company'] = '';
            } else {
                $orderform_arr['company'] = $this->getCompanyName($orderValue['store'], $this->getDomain($orderValue['city_id']), $connect_str, $orderValue['original_amount']);
            }
            
        
            // 商品简述
            $orderform_arr['ordertxt'] = '';
            
            // 订单坐标维度
            if (empty($orderValue['lng'])) {
                $orderform_arr['longitude'] = '';
            } else {
                $orderform_arr['longitude'] = $orderValue['lng'];
            }
            
            // 订单坐标经度
            if (empty($orderValue['lat'])) {
                $orderform_arr['latitude'] = '';
            } else {
                $orderform_arr['latitude'] = $orderValue['lat'];
            }
            
            // 根据送餐时间来判断
            if (intval(substr($orderform_arr['custtime'], 0, 2)) >= 15)
                $cAp = '下午';
            else
                $cAp = '上午';
            // 午别
            $orderform_arr['ap'] = $cAp;
            $orderform_arr['state'] = '订餐';
            // 订单来源
            $orderform_arr['origin'] = $orderValue['refer'];
            // 配送地区标识
            $orderform_arr['domain'] = $this->getDomain($orderValue['city_id']);
            
            // 查询一下是否已经有这个订单
            $where = array();
            $where['ordersn'] = $orderValue['sn'];
            $orderformResult = $orderform_model->where($where)->find();
            if (! empty($orderformResult)) {
                $orderform_model->where($where)->save($orderform_arr);
                $orderformid = $orderformResult['orderformid'];
                // 记入日志
                \Think\Log::write('订单已存在的Sql:' . $orderform_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            } else {
                $orderform_model->create();
                $orderformid = $orderform_model->add($orderform_arr);
                // 记入日志
                \Think\Log::write('订单保存Sql:' . $orderform_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            }
            
            /**
             * ****************************************
             * 订货表处理
             */
            $where = array();
            $where['order_id'] = $orderValue['id'];
            $webOrderGoods = $webordergood_model->where($where)->select();
            // 清理掉已经存在的订货表
            $where = array();
            $where['ordersn'] = $orderValue['sn'];
            $ordergoods_model->where($where)->delete();
            $ordertxt = '';
            $goodsmoney = 0;
            foreach ($webOrderGoods as $orderGoods) {
                // 定义商品数组
                $orderproducts_arr = array();
                // 订单号
                $orderproducts_arr['ordersn'] = $orderValue['sn'];
                // 订单id
                $orderproducts_arr['orderformid'] = $orderformid;
                // 产品code
                $orderproducts_arr['code'] = $this->getProductsCode($orderGoods['good_name'], $orderValue['city_id'], $connect_str);
                // 产品名称
                $orderproducts_arr['name'] = trim($orderGoods['good_name']);
                // 产品简称
                $orderproducts_arr['shortname'] = $this->getProductsShortName($orderGoods['good_name'], $orderValue['city_id'], $connect_str); // 返回产品代码 $orderGoods ['good_short'];
                                                                                                                                               // 产品单价
                $orderproducts_arr['price'] = $orderGoods['good_price'];
                // 产品数量
                $orderproducts_arr['number'] = $orderGoods['good_number'];
                // 产品金额
                $orderproducts_arr['money'] = $orderGoods['good_number'] * $orderGoods['good_price'];
                // 配送地区标识
                $orderproducts_arr['domain'] = $this->getDomain($orderValue['city_id']);
                // 商品简述
                $ordertxt .= $orderproducts_arr['number'] . '×' . $orderproducts_arr['shortname'] . ' ';
                $ordergoods_model->create();
                $ordergoodsid = $ordergoods_model->add($orderproducts_arr);
                // 记入日志
                \Think\Log::write('产品保存Sql:' . $ordergoods_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
                $goodsmoney = $goodsmoney + $orderGoods['good_number'] * $orderGoods['good_price'];
            }
            
            // 按照习惯,将送餐费输入到产品表中
            $goods_tmp = array();
            // 加入送餐费
            if ($orderValue['fee'] > 0) {
                $goods_tmp['orderformid'] = $orderformid;
                $goods_tmp['ordersn'] = $orderValue['sn'];
                $goods_tmp['number'] = 1;
                $goods_tmp['name'] = intval($orderValue['fee']) . 'S';
                $goods_tmp['shortname'] = intval($orderValue['fee']) . 'S';
                $goods_tmp['price'] = $orderValue['fee'];
                $goods_tmp['money'] = $orderValue['fee'];
                $goods_tmp['domain'] = $this->getDomain($orderValue['city_id']);
                $ordergoods_model->create();
                $ordergoodsid = $ordergoods_model->add($goods_tmp);
                // 记入日志
                \Think\Log::write('送餐费保存Sql:' . $ordergoods_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
                $ordertxt .= ' 1×' . $goods_tmp['name']; // 生成产品简述
                $goodsmoney = $goodsmoney + $goods_tmp['number'] * $goods_tmp['price'];
            }
            
            // 清理掉已经存在的结账辅助表
            $where = array();
            $where['ordersn'] = $orderValue['sn'];
            $orderclientdebt_model->where($where)->delete();
            
            /**
             * ******************************************************************
             * 活动表
             */
            $where = array();
            $where['sn'] = $orderValue['sn'];
            $weborderactivity = $weborderactivity_model->where($where)->select();
            // 清理掉已经存在的活动表
            $where = array();
            $where['ordersn'] = $orderValue['sn'];
            $orderactivity_model->where($where)->delete();
            $activitymoney = 0;
            foreach ($weborderactivity as $extra) {
                if ($extra['name'] == '餐盒费') {
                    continue;
                }
                if ($extra['name'] == '餐盒费用') {
                    continue;
                }
                $orderactivity_arr = array();
                $orderactivity_arr['orderformid'] = $orderformid;
                // 订单号
                $orderactivity_arr['ordersn'] = $orderValue['sn'];
                // 活动id
                $orderactivity_arr['activityid'] = $extra['activity_id'];
                // 活动名称
                $orderactivity_arr['name'] = $extra['name'];
                // 活动金额
                $orderactivity_arr['money'] = $extra['discount'];
                // 活动备注
                $orderactivity_arr['note'] = '';
                $orderactivity_model->create();
                $orderactivityid = $orderactivity_model->add($orderactivity_arr);
                // 记入日志
                \Think\Log::write('活动保存Sql:' . $orderactivity_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
                $activitymoney = $activitymoney + $orderactivity_arr['money'];
                
                // 保存活动签单金额
                $clientdebt = array();
                $clientdebt['ordersn'] = $orderValue['sn'];
                $clientdebt['debt_id'] = 0;
                $clientdebt['name'] = $extra['name'];
                $clientdebt['money'] = $extra['discount'];
                $clientdebt['date'] = date('Y-m-d H:i:s');
                $clientdebt['domain'] = $this->getDomain($orderValue['city_id']);
                $orderclientdebt_model->create();
                $orderclientdebt_model->add($clientdebt);
                // 结账用保存日志
                \Think\Log::write('活动结账结账保存Sql:' . $orderclientdebt_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
                
                // 为了结账的需要
                // 活动费
                $data = array();
                $data['ordersn'] = $orderValue['sn'];
                $data['name'] = '官网活动费';
                $data['money'] = $extra['discount'];
                $data['date'] = date('Y-m-d H:i:s');
                $data['domain'] = '';
                $orderfinance_model->create();
                $orderfinance_model->add($data);
            }
            
            /**
             * ******************************************************************
             * 支付表
             */
            $paymentmoney = 0;
            $where = array();
            $where['order_sn'] = $orderValue['sn'];
            $where['pay_money'] = array(
                'GT',
                0
            );
            $weborderpayment = $weborderpayment_model->where($where)->select();
            // 清理掉已经存在的支付表
            $where = array();
            $where['ordersn'] = $orderValue['sn'];
            $orderpayment_model->where($where)->delete();
            $orderpayment_arr = array();
            foreach ($weborderpayment as $payment) {
                // 订单id
                $orderpayment_arr['orderformid'] = $orderformid;
                // 订单号
                $orderpayment_arr['ordersn'] = $orderValue['sn'];
                // 支付ID
                $orderpayment_arr['paymentid'] = $payment['pay_id'];
                // 支付名称
                $orderpayment_arr['name'] = $payment['pay_name'];
                // 支付金额
                $orderpayment_arr['money'] = $payment['pay_money'];
                // 支付备注
                $orderpayment_arr['note'] = '';
                $orderpayment_model->create();
                $orderpayment_model->add($orderpayment_arr);
                // 记入日志
                \Think\Log::write('支付保存Sql:' . $orderpayment_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
                $paymentmoney = $payment['pay_money'];
                
                // 结账修正，改为orderfinance
                // 插入结账的数据
                $data = array();
                $data['ordersn'] = $orderValue['sn'];
                $data['name'] = $payment['pay_name'];
                $data['money'] = $payment['pay_money'];
                $data['date'] = date('Y-m-d H:i:s');
                $data['domain'] = '';
                $orderfinance_model->create();
                $orderfinance_model->add($data);
            }
            
            // 为了结账的需要
            $webOrderGoods = $orderValue['extras'];
            
            foreach ($webOrderGoods as $orderGoods) {
                // 判断是否有货到付款或者在线支付,那么保存的方式是不同的
                if ($orderValue['pay_status'] == 1) {} else {
                    $clientdebt = array();
                    $clientdebt['ordersn'] = $orderValue['sn'];
                    $clientdebt['debt_id'] = 0;
                    $clientdebt['name'] = $orderGoods['remark'];
                    $clientdebt['money'] = $orderGoods['reduce_fee'];
                    $clientdebt['date'] = date('Y-m-d H:i:s');
                    $clientdebt['domain'] = $this->getDomain($orderValue['city_id']);
                    $orderclientdebt_model->create();
                    $orderclientdebt_model->add($clientdebt);
                    // 结账用保存日志
                    \Think\Log::write('结账保存Sql:' . $orderclientdebt_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
                }
            }
            
            if ($orderValue['pay_id'] != 3) {
                $clientdebt = array();
                $clientdebt['ordersn'] = $orderValue['sn'];
                $clientdebt['debt_id'] = 0;
                $clientdebt['name'] = $orderValue['pay_name'];
                $clientdebt['money'] = $orderform_arr['shouldmoney'];
                $clientdebt['date'] = date('Y-m-d H:i:s');
                $clientdebt['domain'] = $this->getDomain($orderValue['city_id']);
                $orderclientdebt_model->create();
                $orderclientdebt_model->add($clientdebt);
                // 结账用保存日志
                \Think\Log::write('结账保存Sql:' . $orderclientdebt_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            }
            
            $data = array();
            // 计算应收金额
            $data['shouldmoney'] = $orderValue['amount'] - $orderValue['money_paid']; // - $paymentmoney - $activitymoney;
                                                                                       // 已付金额
                                                                                       // $data['paidmoney'] = $orderform_arr['money_paid'];
            $data['ordertxt'] = $ordertxt;
            $data['goodsmoney'] = $goodsmoney;
            $where = array();
            $where['orderformid'] = $orderformid;
            $orderform_model->where($where)->save($data);
            // 最终金额保存
            \Think\Log::write('订单最终保存Sql:' . $orderform_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            
            /**
             * *******************************************************************
             */
            // 写入到状态表中
            $data = array();
            $data['create'] = 1;
            $data['createtime'] = date('Y-m-d H:i:s');
            $data['createcontent'] = '网站输入';
            $data['orderformid'] = $orderformid;
            $data['ordersn'] = $orderValue['sn'];
            $data['domain'] = $this->getDomain($orderValue['city_id']);
            $orderstate_model->create();
            $orderstate_model->add($data);
            // 记入日志
            \Think\Log::write('状态保存Sql:' . $orderstate_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            
            // 记入操作到action中
            $action['orderformid'] = $orderformid; // 订单号
            $action['ordersn'] = $orderValue['sn'];
            $action['action'] = '网站' . ' 下载 ' . $orderValue['address'] . ' ' . $ordertxt . ' ' . $orderValue['beizhu'];
            $action['logtime'] = date('H:i:s');
            $action['domain'] = $this->getDomain($orderValue['city_id']);
            $orderaction_model->create();
            $result = $orderaction_model->add($action);

            if(!!$orderform_arr['company']){
                $action['action'] = '订单已分配到【' . $orderform_arr['company'] . '】';
                $orderaction_model->create();
                $result = $orderaction_model->add($action);
            }

            // 记入日志
            \Think\Log::write('日志保存Sql:' . $orderaction_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            
            // 写入到营收状态表,驱动营收结账
            $data = array();
            $data['orderformid'] = $orderformid;
            $data['ordersn'] = $orderValue['sn'];
            $data['status'] = 0;
            $data['assisstatus'] = 1;
            $data['domain'] = $this->getDomain($orderValue['city_id']);
            $orderyingshouexchange_model->create();
            $orderyingshouexchange_model->add($data);
            
            // 写入到网站状态接口表
            $data = array();
            $data['ordersn'] = $orderValue['sn'];
            $data['type'] = 1; // 表示派单
            $data['content'] = "订单确认";
            $data['date'] = date('Y-m-d H:i:s');
            $data['origin'] = $orderValue['refer'];
            $data['domain'] = $this->getDomain($orderValue['city_id']);
            $webstatus_model->create();
            $webstatus_model->add($data);
            
            // 通知客户的消息
            $data = array();
            $data['ordersn'] = $orderValue['sn'];
            $data['telphone'] = '';
            $data['app_tk'] = '';
            $data['contenttype'] = 'confirm';
            $data['origin'] = $orderValue['refer'];
            $data['domain'] = $this->getDomain($orderValue['city_id']);
            $notifyclientModel->create();
            $notifyclientModel->add($data);
            
            // 保存发票,发票处理
            if (! empty($orderValue['inv_payee'])) {
                $data = array();
                $data['header'] = substr($orderValue['inv_payee'], 0, 80);
                $data['body'] = $orderform_arr['invoicebody'];
                $data['gmf_nsrsbh'] = $orderform_arr['gmf_nsrsbh'];
                $data['gmf_dzdh'] = $orderform_arr['gmf_dzdh'];
                $data['gmf_yhzh'] = $orderform_arr['gmf_yhzh'];
                $data['type'] = $orderValue['inv_type']; // 2普通发票，3电子发票
                $data['ordersn'] = $orderValue['sn'];
                $data['orderformtxt'] = $orderform_arr['address'] . ' ' . $ordertxt;
                $data['ordermoney'] = $orderform_arr['totalmoney'] - $activitymoney;
                $data['ordertime'] = date('H:i:s');
                $data['state'] = '未开';
                if (! empty($orderValue['store'])) {
                    $data['company'] = $orderValue['store'];
                } else {
                    $data['company'] = '';
                }
                $data['domain'] = $this->getDomain($orderValue['city_id']);
                $invoice_model->create();
                $invoice = $invoice_model->add($data);
                // 记入日志
                \Think\Log::write('发票保存Sql:' . $invoice_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            }
            
            /**
             * ***************************************************************
             */
            // 设置订单已经传递给rms
            $where = array();
            $where['sn'] = $orderValue['sn'];
            $data = array();
            $data['status'] = 1;
            $weborder_model->where($where)->save($data);
        }
    }

    // 返回产品代码
    public function getProductsCode($name, $domain, $connect_str)
    {
        // 产品表
        $products_model = M('products', 'rms_', $connect_str);
        $where = array();
        $where['name'] = trim($name);
        $where['domain'] = $this->getDomain($domain);
        $products = $products_model->where($where)->find();
        if ($products) {
            return $products['code'];
        } else {
            return '';
        }
    }

    // 获取产品简称
    public function getProductsShortName($name, $domain, $connect_str)
    {
        // 产品表
        $products_model = M('products', 'rms_', $connect_str);
        $where = array();
        $where['name'] = trim($name);
        $where['domain'] = $this->getDomain($domain);
        $products = $products_model->where($where)->find();
        if ($products) {
            return $products['shortname'];
        } else {
            return $name;
        }
    }

    function getDomain($supperliers_id)
    {
        switch ($supperliers_id) {
            case 1:
                $domain = 'bj.lihuaerp.com';
                break;
            case 3:
                $domain = 'sh.lihuaerp.com';
                break;
            case 4:
                $domain = 'cz.lihuaerp.com';
                break;
            case 6:
                $domain = 'nj.lihuaerp.com';
                break;
            case 7:
                $domain = 'sz.lihuaerp.com';
                break;
            case 8:
                $domain = 'wx.lihuaerp.com';
                break;
            case 9:
                $domain = 'gz.lihuaerp.com';
                break;
        }
        return $domain;
    }

    /**
     *
     * @param
     *            $text
     * @return string
     */
    
    // 删除特殊的字符
    private function filter($text)
    {
        $text = str_replace("`", "", $text);
        $text = str_replace("'", "", $text);
        $text = str_replace("~", "", $text);
        $text = str_replace('"', "", $text);
        $text = str_replace('　', " ", $text);
        // $text = str_replace('发票', "", $text);
        return htmlspecialchars($text, ENT_QUOTES);
    }

    // 简化日志方法
    private function log($msg)
    {
        // 定义日志文件
        $LogFile = C('LOG_PATH') . 'web_' . date('Y_m_d') . ".log";
        
        // 记入日志
        LOG::write($msg, LOG::INFO, '', $LogFile);
    }

    /**
     * ****************************************************************************************
     */
    // 获取rms中webstate, 写入网站中
    // /alidata/server/php/bin/php /home/rmsdaemon/index.php Home/LihuaWeb/setGzWebStatus
    public function setCzWebStatus()
    {
        $this->logFile = C('LOG_PATH') . 'Gzwebstate-' . date('y_m_d') . '.log';
        $this->setWebStatus(4);
    }

    public function setBjWebStatus()
    {
        $this->logFile = C('LOG_PATH') . 'Bjwebstate-' . date('y_m_d') . '.log';
        $this->setWebStatus(1);
    }

    public function setNjWebStatus()
    {
        $this->logFile = C('LOG_PATH') . 'Njwebstate-' . date('y_m_d') . '.log';
        $this->setWebStatus(6);
    }

    public function setWxWebStatus()
    {
        $this->logFile = C('LOG_PATH') . 'Wxwebstate-' . date('y_m_d') . '.log';
        $this->setWebStatus(8);
    }

    public function setSzWebStatus()
    {
        $this->logFile = C('LOG_PATH') . 'Szwebstate-' . date('y_m_d') . '.log';
        $this->setWebStatus(7);
    }

    public function setShWebStatus()
    {
        $this->logFile = C('LOG_PATH') . 'Shwebstate-' . date('y_m_d') . '.log';
        $this->setWebStatus(3);
    }

    public function setGzWebStatus()
    {
        $this->logFile = C('LOG_PATH') . 'Gzwebstate-' . date('y_m_d') . '.log';
        $this->setWebStatus(9);
    }

    function setWebStatus($city_id)
    {
        \Think\Log::write('开始获取网站的订单', \Think\Log::INFO, '', $this->logFile);
        if ($city_id == 1) {
            $connect_str = C('BJRMS_CONNECTSTR');
        } else {
            $connect_str = C('RMS_CONNECTSTR');
        }
        
        // 订单表
        $webstatus_model = M('webstatus', 'rms_', $connect_str);
        
        $lihuaweb_conn_str = C('LIHUAWEB_CONNETCSTR');
        
        // 网站订单表
        $weborder_model = M('order', 'lihua_think_', $lihuaweb_conn_str);
        // 网站配送表
        $weborderlogistics_model = M('order_logistics', 'lihua_think_', $lihuaweb_conn_str);
        
        $where = array();
        // 配送地区标识
        $where['domain'] = $this->getDomain($city_id);
        $where['state'] = 0;
        $where['origin'] = array(
            array(
                'like',
                '%网站%'
            ),
            array(
                'like',
                '%触屏%'
            ),
            array(
                'like',
                '%APP%'
            ),
            array(
                'like',
                '%微信%'
            ),
            array(
                'like',
                '%小程序%'
            ),
            'OR'
        );
        $webstatusResult = $webstatus_model->where($where)
            ->limit(30)
            ->select();

        //var_dump($webstatus_model->getLastSql());
        var_dump($webstatusResult);

        foreach ($webstatusResult as $statusValue) {
            $ordersn = $statusValue['ordersn'];
            // 状态写入网站订单表
            $where = array();
            $where['sn'] = $ordersn;
            $data = array();
            $data['status'] = $statusValue['type'];
            $weborder_model->where($where)->save($data);

            //var_dump($weborder_model->getLastSql());
            //var_dump($weborder_model->getLastSql());
            
            // 状态写入配送表
            $data = array();
            $data['order_sn'] = $ordersn;
            $data['desc'] = $statusValue['content'];
            $data['add_time'] = date('Y-m-d H:i:s');
            $weborderlogistics_model->create();
            $weborderlogistics_model->add($data);
            
            // 将state 设置 1
            $where = array();
            $where['ordersn'] = $ordersn;
			$where['webstatus'] = $statusValue['webstatus'];
            $data = array();
            $data['state'] = 1;
            $webstatus_model->where($where)->save($data);

            var_dump($webstatus_model->getLastSql());
        }
    }

    /**
     * 替换字符串中含有的字
     * 
     * @param unknown_type $str
     *            ：utf-8编码过的字符串
     */
    function checkstr($str, $needle)
    {
        $str = urlencode($str);
        $needle = urlencode($needle);
        
        // 判断是不是含有'市'
        if (strpos($str, $needle) !== false) {
            // 有,进行替换
            $str = str_replace($needle, '', $str);
        }
        // 按照16进制解码解码然后返回
        return urldecode($str);
    }

    /**
     * 为了判断金额是否大于自动分配的要求，做一个自动分配的拦截函数
     */
    function getCompanyName($value, $domain, $connect_str, $totalmoney)
    {
        
        if($domain == 'sh.lihuaerp.com') {
            
            if ($value == '方正证券') { return '延安'; }
            if ($value == '闸新医院') { return '江场'; }
            if ($value == '赛科斯') { return '江场'; }
            
            if ($value == '盛思锐') {
                return '闵行';
            }
            if ($value == '星巴克') {
                return '闵行';
            }
            if ($value == '卓盟国际') {
                return '延安';
            }
            if ($value == '瑞莱科技') {
                return '闵行';
            }
            if ($value == '台商子女学校') {
                return '国展';
            }
            if ($value == '天安人寿') {
                return '陆家嘴';
            }            
            if ($value == '上海众毅') {
                return '黄浦';
            }            
            if ($value == '上海齐家网') {
                return '真北';
            }   
            
            if ($value == '鸿海大厦') {
                return '真北';
            } 
            
            if ($value == '绿神生态园艺') {
                return '杨浦';
            }
            
            if ($value == '闯奇科技') {
                return '杨浦';
            }
            
            if ($value == '极橙口腔') { 
                return '陆家嘴';
            } 
            if ($value == '光音广场') {
                return '陆家嘴';
            } 
            
            if ($value == '上海探真') {
                return '杨浦';
            } 
            
            if ($value == '招商局') {
                return '普陀';
            } 
            
            if ($value == '游泳馆') {
                return '浦东';
            } 
            
            if ($value == '爱新液化') {
                return '虹口';
            } 
            
            if ($value == '中远海运') {
                return '虹口';
            } 
            
            if ($value == '顺丰速运') {
                return '陆家嘴';
            }
			if ($value == '国际货币') {
			    return '陆家嘴';
			} 
            if ($value == '谷露软件') {
                return '外滩';
            } 
            if ($value == '跃盛') {
                return '闵行';
            }
            if ($value == '上海翔乐') {
                return '宝山';
            }
            if ($value == '祥乐田村') {
                return '宝山';
            }
            if ($value == '宝林物业') {
                return '江场';
            }
            if ($value == '贝海网络') { return '普陀'; }
            if ($value == '上海电气') { return '江场'; }
            if ($value == '中国外汇交易中心' || $value == '中国基督教协会') { return '外滩'; }
			// if ( $value=='金桥' || $value=='张江' || $value=='陆家嘴' || $value=='宝山' || $value=='杨浦' ) {
			//     return '';
            // }
            return "";
        }

        if($domain == 'sz.lihuaerp.com') {
            // if ($value == '圆融') { return ''; }
            // if ($value == '胜浦') { return ''; }
        }

        if($domain == 'nj.lihuaerp.com') {
            if ($value == '黄山路') { return ''; }
            if ($value == '白下路') { return ''; }
            if ($value == '财大') { return ''; }
            if ($value == '徐庄') { return ''; }
            if ($value == '云龙山路') { return ''; }
            if ($value == '迈皋桥') { return ''; }            
        }

        if($domain == 'wx.lihuaerp.com') {
            if ($value == '南洋银行') { return '人民路'; }
            if ($value == '904医院') { return '凤翔'; }
            if ($value == '金泰') { return ''; }
            if ($value == '太湖') { return ''; }
            if ($value == '凤翔') { return ''; }
            if ($value == '新区') { return ''; }
            if ($value == '人民路') { return ''; }
            if ($value == '清扬') { return ''; }
            if ($value == '五爱') { return ''; }
            if ($value == '丽华生鲜(无锡)') { return ''; }
            if ($value == '百脑汇') { return '五爱'; }
            if ($value == '南京银行') { return '凤翔'; }
            if ($value == '海康威视') { return '凤翔'; }
            if ($value == '新由物业') { return '清扬'; }
            if ($value == '节能环保大厦') { return '五爱'; }
        }
        //北京地区春节期间关店 通州、奥体、中关村、丰台、国贸、朝阳门、石景山、亦庄、工体

        // 工体 王府井 北科大 酒仙桥 丰台 开发区
        // 通州，菜户营 ，工体，望京，中关村
        // 国贸 北科大 奥体 酒仙桥 石景山 光彩 西二环 丰台
        // 亦庄 东五环 永定门 工体 望京 亚运村 北三环 西二环 西四环
        // 北京地区 亦庄店 、东五环店 、永定门店、工体店、望京店、亚运村店、北三环店、西二环店、西四环店

        if($domain == 'bj.lihuaerp.com') {
            if($value == '农展店'){  return '工体'; }
            // if($value == '亚运村'){  return ''; }
            // if($value == '亚运村店'){  return ''; }
            // if($value == '中关村'){  return ''; }
            // if($value == '中关村店'){  return ''; }
            // if($value == '北工大'){  return ''; }
            // if($value == '朝阳门'){  return ''; }
            // if($value == '奥体'){  return ''; }
            if($value == '月坛'){  return ''; }
            // if($value == '石景山'){  return ''; }
            // if($value == '菜户营'){  return ''; }
            // if($value == '北科大'){  return ''; }
            // if($value == '工体'){  return ''; }
            // if($value == '首体'){  return ''; }
            // if($value == '通州店'){  return ''; }
            // if($value == '丰台'){  return ''; }
            // if($value == '国贸'){  return ''; }
            // if($value == '亦庄'){  return ''; }
            // if($value == '亦庄店'){  return ''; }
            // if($value == '东五环'){  return ''; }
            // if($value == '永定门'){  return ''; }
            // if($value == '望京'){  return ''; }
            // if($value == '北三环'){  return ''; }
            // if($value == '西二环'){  return ''; }
            // if($value == '西客站'){  return ''; }
            // if($value == '光彩'){  return ''; }
            // if($value == '西四环'){  return ''; }
	        // if($value == '王府井'){  return ''; }
            // if($value == '酒仙桥'){  return ''; }
            // if($value == '开发区'){  return ''; }
        }
        //常州地区满300取消自动分配
        if($domain == 'cz.lihuaerp.com'){
            if((int)$totalmoney>=300){
                return '';
            }
        }
        // 增加判断，如果参数中的金额大于设定值，就不能自动分配
        $companyparam_model = M('companyparam', 'rms_', $connect_str);
        $where = array();
        $where['domain'] = $domain;
        $companyparam = $companyparam_model->where($where)->find();
              
        if (! empty($companyparam['noautomoney'])) {
            // 大于金额，直接返回空
            if (($totalmoney - $companyparam['noautomoney']) >= 0) {
                return '';
            } else {
                return $value;
            }
        }
        
        return $value;
    }

    // 空方法
    public function _empty()
    {
        var_dump('empty');
    }

    /**
     * *********************************************************
     */
    /**
     * /alidata/server/php/bin/php /home/rmsdaemon/index.php Home/LihuaWeb/getShBookOrder
     * /alidata/server/php/bin/php /home/rmsdaemon/index.php Home/LihuaWeb/getWxBookOrder
     */
    
    // 获取上海的订单
    public function getShBookOrder()
    {
        $this->logFile = C('LOG_PATH') . 'bookweborderSh-' . date('y_m_d') . '.log';
        \Think\Log::write('开始获取网站的订单', \Think\Log::INFO, '', $this->logFile);
        
        $connect_str = C('RMS_CONNECTSTR');
        $this->bookOrderDump(3, $connect_str);
    }

    public function getWxBookOrder()
    {
        $this->logFile = C('LOG_PATH') . 'bookweborderSh-' . date('y_m_d') . '.log';
        \Think\Log::write('开始获取网站的订单', \Think\Log::INFO, '', $this->logFile);
        
        $connect_str = C('RMS_CONNECTSTR');
        $this->bookOrderDump(8, $connect_str);
    }

    /**
     * 导出预订的数据，到预订单中
     */
    public function bookOrderDump($city_id, $connect_str)
    {
        
        // 订单表
        $orderform_model = M('bookorder', 'rms_', $connect_str);
        // 订货表
        $ordergoods_model = M('bookproducts', 'rms_', $connect_str);
        // 活动表
        $orderactivity_model = M('bookactivity', 'rms_', $connect_str);
        // 支付表
        $orderpayment_model = M('bookpayment', 'rms_', $connect_str);
        // 日志表action中
        $orderaction_model = M('bookaction', 'rms_', $connect_str);
        // 网站状态表
        $webstatus_model = M('webstatus', 'rms_', $connect_str);
        // 营收状态表
        $orderyingshouexchange_model = M('orderyingshouexchange', 'rms_', $connect_str);
        // 发票,不写入,等分配订单的时候,写入
        $invoice_model = M('invoice', 'rms_', $connect_str);
        
        $lihuaweb_conn_str = C('LIHUAWEB_CONNETCSTR');
        // 网站订单表
        $weborder_model = M('order', 'lihua_think_', $lihuaweb_conn_str);
        // 网站产品表
        $webordergood_model = M('order_good', 'lihua_think_', $lihuaweb_conn_str);
        // 网站活动表
        $weborderactivity_model = M('order_activity', 'lihua_think_', $lihuaweb_conn_str);
        // 网站支付表
        $weborderpayment_model = M('order_payment', 'lihua_think_', $lihuaweb_conn_str);
        
        $currentDate = date('Y-m-d', strtotime('+1 day'));
        
        $where = array();
        $where['city_id'] = $city_id;
        $where['status'] = 0;
        // $where['_string'] = " (pay_status = 1 or pay_status = 2) and (add_time >= '" . $currentDate . "') ";
        // $where['pay_status'] = 2;
		// $where['pay_status'] = array(1,2,'_logic'=>'or');
		$where['shipping_time'] = array('EGT', $currentDate);
		$where['pay_status'] = array('EGT', 1);
        $orderform = $weborder_model->where($where)
            ->limit(50)
            ->order('id desc')
            ->select();
        
        // var_dump($weborder_model->getLastSql());
        
        \Think\Log::write('获取' . $weborder_model->getLastSql() . ' ', \Think\Log::INFO, '', $this->logFile);
        
        // 写入日志
        \Think\Log::write('获取' . count($orderform) . '条订单', \Think\Log::INFO, '', $this->logFile);
        foreach ($orderform as $orderValue) {
            
            /**
             * *********************************
             * 订单表处理
             * *********************************
             */
            $orderform_arr = array();
            // 订单号
            $orderform_arr['ordersn'] = $orderValue['sn'];
            // 联系人的姓名
            $orderform_arr['clientname'] = $orderValue['consignee'];
            
            // 用户送餐地址
            if (empty($orderValue['location'])) {
                $orderform_arr['address'] = $orderValue['address'];
            } else {
                $address_tmp = $orderValue['address'];
                $topheader = '';
                for ($i = 0; $i < 10; $i ++) { // 循环十次
                    $toptmp = substr($address_tmp, 0, 1);
                    if ($toptmp == '(') {
                        $topheaderlength = strpos($address_tmp, ')', 1);
                        $topheader = $topheader . substr($address_tmp, 0, $topheaderlength + 1);
                        $address_tmp = substr($address_tmp, $topheaderlength + 1);
                    }
                }
                $location = $this->checkstr($address_tmp, $orderValue['location']); // 去掉重复的地址
                $orderform_arr['address'] = $topheader . $orderValue['location'] . $location;
            }
            
            $orderform_arr['address'] = $this->filter($orderform_arr['address']);
            // 收货人手机
            $orderform_arr['telphone'] = $orderValue['tel'];
            $orderform_arr['telphone'] = $this->filter($orderform_arr['telphone']);
            // 预订送餐日期
            $orderform_arr['bookdate'] = substr($orderValue['shipping_time'], 0, 10);
            // 送餐时间
            if (empty($orderValue['time'])) {
                $orderform_arr['custtime'] = date('H:i:s', time() + 60 * 30);
            } else {
                $orderform_arr['custtime'] = $orderValue['time'];
            }
            // 接单员
            $orderform_arr['telname'] = $orderValue['refer'];
            // 接单时间
            $orderform_arr['rectime'] = date('H:i:s');
            // 接单日期
            $orderform_arr['recdate'] = date('Y-m-d');
            // 订单备注(附言)
            $orderform_arr['beizhu'] = $orderValue['remark'];
            $orderform_arr['beizhu'] = $this->filter($orderform_arr['beizhu']);
            if ($city_id == 4) {
                $orderform_arr['beizhu'] = '[网订]' . $orderform_arr['beizhu'];
            }
            
            // 订单总金额
            $orderform_arr['totalmoney'] = $orderValue['original_amount'];
            // 应收金额
            $orderform_arr['shouldmoney'] = $orderValue['amount'];
            // 已付金额
            $orderform_arr['paidmoney'] = $orderValue['money_paid'];
            
            if ($orderValue['pay_type'] == 2) { // 是在线支付
                                                    // 已付金额
                                                    // $orderform_arr['paidmoney'] = 0;
                                                    // 应收金额
                                                    // $orderform_arr['shouldmoney'] = 0;
            } else { // 是货到付款
                         // 已付金额
                         // $orderform_arr['paidmoney'] = 0;
                         // 应收金额
                         // $orderform_arr['shouldmoney'] = 0;
            }
            
            // 发票抬头
            if (! empty($orderValue['inv_payee'])) {
                $orderform_arr['invoiceheader'] = $orderValue['inv_payee'];
            } else {
                $orderform_arr['invoiceheader'] = '';
            }
            // 发票内容
            if (! empty($orderValue['inv_content'])) {
                $orderform_arr['invoicebody'] = $orderValue['inv_content'];
            } else {
                $orderform_arr['invoicebody'] = '工作餐';
            }
            // 纳税人识别号
            if (! empty($orderValue['inv_no'])) {
                if (trim($orderValue['inv_no']) == '无') {
                    $orderform_arr['gmf_nsrsbh'] = '';
                } else {
                    $orderform_arr['gmf_nsrsbh'] = $orderValue['inv_no'];
                }
            } else {
                $orderform_arr['gmf_nsrsbh'] = '';
            }
            // 购买方地址电话
            if (! empty($orderValue['inv_addressandtel'])) {
                $orderform_arr['gmf_dzdh'] = $orderValue['inv_addressandtel'];
            } else {
                $orderform_arr['gmf_dzdh'] = '';
            }
            // 购买方银行账户
            if (! empty($orderValue['inv_bankandaccount'])) {
                $orderform_arr['gmf_yhzh'] = $orderValue['inv_bankandaccount'];
            } else {
                $orderform_arr['gmf_yhzh'] = '';
            }
            // 发票类型
            if ($orderValue['inv_type'] == 2) {
                $orderform_arr['invoicetype'] = '普通票';
            }
            if ($orderValue['inv_type'] == 3) {
                $orderform_arr['invoicetype'] = '电子票';
            }
            
            // 送餐费名称
            $orderform_arr['shippingname'] = '自配送';
            // 送餐费金额
            $orderform_arr['shippingmoney'] = 0;
            
            // 分公司名称（商店）
            if (empty($orderValue['store'])) {
                $orderform_arr['company'] = '';
            } else {
                $orderform_arr['company'] = $this->getCompanyName($orderValue['store'], $this->getDomain($orderValue['city_id']), $connect_str, $orderValue['original_amount']);
            }
            
            // 商品简述
            $orderform_arr['ordertxt'] = '';
            
            // 订单坐标维度
            if (empty($orderValue['lng'])) {
                $orderform_arr['longitude'] = '';
            } else {
                $orderform_arr['longitude'] = $orderValue['lng'];
            }
            
            // 订单坐标经度
            if (empty($orderValue['lat'])) {
                $orderform_arr['latitude'] = '';
            } else {
                $orderform_arr['latitude'] = $orderValue['lat'];
            }
            
            // 根据送餐时间来判断
            if (intval(substr($orderform_arr['custtime'], 0, 2)) >= 15)
                $cAp = '下午';
            else
                $cAp = '上午';
            // 午别
            $orderform_arr['ap'] = $cAp;
            $orderform_arr['state'] = '预订';
            // 订单来源
            $orderform_arr['origin'] = $orderValue['refer'];
            // 配送地区标识
            $orderform_arr['domain'] = $this->getDomain($orderValue['city_id']);
            
            // 查询一下是否已经有这个订单
            $where = array();
            $where['ordersn'] = $orderValue['sn'];
            $orderformResult = $orderform_model->where($where)->find();
            if (! empty($orderformResult)) {
                $orderform_model->where($where)->save($orderform_arr);
                $orderformid = $orderformResult['orderformid'];
                // 记入日志
                \Think\Log::write('订单已存在的Sql:' . $orderform_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            } else {
                $orderform_model->create();
                $orderformid = $orderform_model->add($orderform_arr);
                // 记入日志
                \Think\Log::write('订单保存Sql:' . $orderform_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            }
            
            /**
             * ****************************************
             * 订货表处理
             */
            $where = array();
            $where['order_id'] = $orderValue['id'];
            $webOrderGoods = $webordergood_model->where($where)->select();
            // 清理掉已经存在的订货表
            $where = array();
            $where['ordersn'] = $orderValue['sn'];
            $ordergoods_model->where($where)->delete();
            $ordertxt = '';
            $goodsmoney = 0;
            foreach ($webOrderGoods as $orderGoods) {
                // 定义商品数组
                $orderproducts_arr = array();
                // 订单id
                $orderproducts_arr['bookorderid'] = $orderformid;
                // 产品code
                $orderproducts_arr['code'] = $this->getProductsCode($orderGoods['good_name'], $orderValue['city_id'], $connect_str);
                // 产品名称
                $orderproducts_arr['name'] = $orderGoods['good_name'];
                // 产品简称
                $orderproducts_arr['shortname'] = $this->getProductsShortName($orderGoods['good_name'], $orderValue['city_id'], $connect_str); // 返回产品代码 $orderGoods ['good_short'];
                                                                                                                                               // 产品单价
                $orderproducts_arr['price'] = $orderGoods['good_price'];
                // 产品数量
                $orderproducts_arr['number'] = $orderGoods['good_number'];
                // 产品金额
                $orderproducts_arr['money'] = $orderGoods['good_number'] * $orderGoods['good_price'];
                // 配送地区标识
                $orderproducts_arr['domain'] = $this->getDomain($orderValue['city_id']);
                // 商品简述
                $ordertxt .= $orderproducts_arr['number'] . '×' . $orderproducts_arr['shortname'] . ' ';
                $ordergoods_model->create();
                $ordergoodsid = $ordergoods_model->add($orderproducts_arr);
                // 记入日志
                \Think\Log::write('产品保存Sql:' . $ordergoods_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
                $goodsmoney = $goodsmoney + $orderGoods['good_number'] * $orderGoods['good_price'];
            }
            
            // 按照习惯,将送餐费输入到产品表中
            $goods_tmp = array();
            // 加入送餐费
            if ($orderValue['fee'] > 0) {
                $goods_tmp['bookorderid'] = $orderformid;
                $goods_tmp['number'] = 1;
                $goods_tmp['name'] = intval($orderValue['fee']) . 'S';
                $goods_tmp['shortname'] = intval($orderValue['fee']) . 'S';
                $goods_tmp['price'] = $orderValue['fee'];
                $goods_tmp['money'] = $orderValue['fee'];
                $goods_tmp['domain'] = $this->getDomain($orderValue['city_id']);
                $ordergoods_model->create();
                $ordergoodsid = $ordergoods_model->add($goods_tmp);
                // 记入日志
                \Think\Log::write('送餐费保存Sql:' . $ordergoods_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
                $ordertxt .= ' 1×' . $goods_tmp['name']; // 生成产品简述
                $goodsmoney = $goodsmoney + $goods_tmp['number'] * $goods_tmp['price'];
            }
            
            /**
             * ******************************************************************
             * 活动表
             */
            $where = array();
            $where['sn'] = $orderValue['sn'];
            $weborderactivity = $weborderactivity_model->where($where)->select();
            // 清理掉已经存在的活动表
            $where = array();
            $where['ordersn'] = $orderValue['sn'];
            $orderactivity_model->where($where)->delete();
            $activitymoney = 0;
            foreach ($weborderactivity as $extra) {
                $orderactivity_arr = array();
                $orderactivity_arr['bookorderid'] = $orderformid;
                // 订单号
                $orderactivity_arr['ordersn'] = $orderValue['sn'];
                // 活动id
                $orderactivity_arr['activityid'] = $extra['activity_id'];
                // 活动名称
                $orderactivity_arr['name'] = $extra['name'];
                // 活动金额
                $orderactivity_arr['money'] = $extra['discount'];
                // 活动备注
                $orderactivity_arr['note'] = '';
                $orderactivity_model->create();
                $orderactivityid = $orderactivity_model->add($orderactivity_arr);
                // 记入日志
                \Think\Log::write('活动保存Sql:' . $orderactivity_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
                $activitymoney = $activitymoney + $orderactivity_arr['money'];
                
                // 保存活动签单金额
                $clientdebt = array();
                $clientdebt['ordersn'] = $orderValue['sn'];
                $clientdebt['debt_id'] = 0;
                $clientdebt['name'] = $extra['name'];
                $clientdebt['money'] = $extra['discount'];
                $clientdebt['date'] = date('Y-m-d H:i:s');
                $clientdebt['domain'] = $this->getDomain($orderValue['city_id']);
                $orderclientdebt_model->create();
                $orderclientdebt_model->add($clientdebt);
                // 结账用保存日志
                \Think\Log::write('活动结账结账保存Sql:' . $orderclientdebt_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            }
            
            /**
             * ******************************************************************
             * 支付表
             */
            $paymentmoney = 0;
            $where = array();
            $where['order_sn'] = $orderValue['sn'];
            $where['pay_money'] = array(
                'GT',
                0
            );
            $weborderpayment = $weborderpayment_model->where($where)->select();
            // 清理掉已经存在的支付表
            $where = array();
            $where['ordersn'] = $orderValue['sn'];
            $orderpayment_model->where($where)->delete();
            $orderpayment_arr = array();
            foreach ($weborderpayment as $payment) {
                // 订单id
                $orderpayment_arr['bookorderid'] = $orderformid;
                // 订单号
                $orderpayment_arr['ordersn'] = $orderValue['sn'];
                // 支付ID
                $orderpayment_arr['paymentid'] = $payment['pay_id'];
                // 支付名称
                $orderpayment_arr['name'] = $payment['pay_name'];
                // 支付金额
                $orderpayment_arr['money'] = $payment['pay_money'];
                // 支付备注
                $orderpayment_arr['note'] = '';
                $orderpayment_model->create();
                $orderpayment_model->add($orderpayment_arr);
                // 记入日志
                \Think\Log::write('支付保存Sql:' . $orderpayment_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
                $paymentmoney = $payment['pay_money'];
            }
            
            $data = array();
            // 计算应收金额
            $data['shouldmoney'] = $orderValue['amount'] - $orderValue['money_paid']; // - $paymentmoney - $activitymoney;
                                                                                      // 已付金额
                                                                                      // $data['paidmoney'] = $orderform_arr['money_paid'];
            $data['ordertxt'] = $ordertxt;
            $data['goodsmoney'] = $goodsmoney;
            $where = array();
            $where['bookorderid'] = $orderformid;
            $orderform_model->where($where)->save($data);
            // 最终金额保存
            \Think\Log::write('订单最终保存Sql:' . $orderform_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            
            // 记入操作到action中
            $action['bookorderid'] = $orderformid; // 订单号
            $action['ordersn'] = $orderValue['sn'];
            $action['action'] = '网站' . ' 下载 ' . $orderValue['address'] . ' ' . $ordertxt . ' ' . $orderValue['beizhu'];
            $action['logtime'] = date('H:i:s');
            $action['domain'] = $this->getDomain($orderValue['city_id']);
            $orderaction_model->create();
            $result = $orderaction_model->add($action);

            if(!!$orderform_arr['company']){
                $action['action'] = '订单已分配到【' . $orderform_arr['company'] . '】';
                $orderaction_model->create();
                $result = $orderaction_model->add($action);
            }

            // 记入日志
            \Think\Log::write('日志保存Sql:' . $orderaction_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            
            // 写入到网站状态接口表
            $data = array();
            $data['ordersn'] = $orderValue['sn'];
            $data['type'] = 1; // 表示派单
            $data['content'] = "订单确认";
            $data['date'] = date('Y-m-d H:i:s');
            $data['origin'] = $orderValue['refer'];
            $data['domain'] = $this->getDomain($orderValue['city_id']);
            $webstatus_model->create();
            $webstatus_model->add($data);
            
            // 保存发票,发票处理
            if (! empty($orderValue['inv_payee'])) {
                $data = array();
                $data['header'] = substr($orderValue['inv_payee'], 0, 80);
                $data['body'] = $orderform_arr['invoicebody'];
                $data['gmf_nsrsbh'] = $orderform_arr['gmf_nsrsbh'];
                $data['gmf_dzdh'] = $orderform_arr['gmf_dzdh'];
                $data['gmf_yhzh'] = $orderform_arr['gmf_yhzh'];
                $data['type'] = $orderValue['inv_type']; // 2普通发票，3电子发票
                $data['ordersn'] = $orderValue['sn'];
                $data['orderformtxt'] = $orderform_arr['address'] . ' ' . $ordertxt;
                $data['ordermoney'] = $orderform_arr['totalmoney'] - $activitymoney;
                $data['ordertime'] = date('H:i:s');
                $data['state'] = '未开';
                if (! empty($orderValue['store'])) {
                    $data['company'] = $orderValue['store'];
                } else {
                    $data['company'] = '';
                }
                $data['domain'] = $this->getDomain($orderValue['city_id']);
                $invoice_model->create();
                $invoice = $invoice_model->add($data);
                // 记入日志
                \Think\Log::write('发票保存Sql:' . $invoice_model->getLastSql(), \Think\Log::INFO, '', $this->logFile);
            }
            
            /**
             * ***************************************************************
             */
            // 设置订单已经传递给rms
            $where = array();
            $where['sn'] = $orderValue['sn'];
            $data = array();
            $data['status'] = 1;
            $weborder_model->where($where)->save($data);
        }
    }
}
